import {batchDeleteItem, changeSelectState, getShopCartList} from "@mall/api/shopCart"
import {freightFee, preOrderFun} from "@mall/api/order";
import router from "@src/router";
import {storeBindingsBehavior} from "mobx-miniprogram-bindings";
import base from "@src/store/base";
import mall from "@src/store/mall";

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeTitleColor', 'themeColor'],
  },{
    store: mall,
    fields: ['curLocation']
  }],
  properties: {
    storeId: {
      type: Number
    },
    store: {
      type: Object
    },
    deliveryType: {
      type: String
    },
  },
  data: {
    totalFee: 0,
    count: 0,
    contentHeight: 90,
    cartItems: [],
    selectCartItems: [],
    selectAll: false,
    canDelivery: true,
    supplyDelivery: true,
    errorMsg: false,
    dialogShow: false,
  },
  observers: {
    'storeId': function (storeId) {
      if (storeId) {
        this.fetchData();
      }
    },
    'store,deliveryType': function (store,deliveryType) {
      if (store && deliveryType) {
        if (deliveryType ==='SELF_PICKUP') {
          this.setData({supplyDelivery: store.delivery.supplySelfPickup})
        } else {
          this.setData({supplyDelivery: store.delivery.supplyLocal})
        }
      }
    },
    'curLocation,count,selectCartItems,deliveryType': function (curLocation,count,selectCartItems,deliveryType) {
      if (count === 0) {
        this.setData({canDelivery: false, errorMsg: ''});
        return;
      }
      if (deliveryType === 'SELF_PICKUP') {
        this.setData({canDelivery: true, errorMsg: ''});
        return;
      }
      if (!curLocation) {
        // 不做判断
        this.setData({canDelivery: true, errorMsg: ''});
        return;
      }
      this.fetchFreightFee(curLocation, count, selectCartItems, deliveryType)
    }
  },
  methods: {
    handleShow() {
      this.setData({dialogShow: !this.data.dialogShow})
    },
    handleClose() {
      this.setData({dialogShow: false})
    },
    handleContentHeight(e) {
      this.setData({contentHeight: e.detail})
    },
    refresh() {
      this.fetchData();
    },
    fetchData() {
      let storeId = this.data.storeId;
      let data = {
        storeId: storeId,
        type: 'LOCAL',
        cartType: 0
      }
      getShopCartList(data).then(res => {
        let cartList = res.data;
        let cart = null;
        if (cartList && cartList.length > 0) {
          cart = cartList[0];
        }
        if (cart == null) {
          this.setData({totalFee: 0, selectAll: false, cartItems: [], dialogShow:false})
          return;
        }
        let cartItems = JSON.parse(JSON.stringify(cart.items));
        let invalidItems = JSON.parse(JSON.stringify(cart.invalidItems));
        for(let i = 0; i < cartItems.length; i++) {
          cartItems[i].disable = false;
        }
        for(let i = 0; i < invalidItems.length;i++) {
          invalidItems[i].disable = true;
          cartItems.push(invalidItems[i]);
        }
        this.setData({cart: cart, cartItems: cartItems})
        if (cart.errorCode === 0) {
          this.initCart(this.data.cartItems);
        } else {
          this.setData({selectCartItems: [], selectAll: false, totalFee: 0, count: 0})
        }
      })
    },
    fetchFreightFee(curLocation, count, selectCartItems, deliveryType) {
      let storeId = this.data.storeId;
      if (!storeId ) {
        return;
      }
      let data = {
        storeId: storeId,
        type: deliveryType,
        items: selectCartItems,
        deliveryInfo: curLocation,
        source: {}
      }
      freightFee(data).then(res => {
        let result = res.data
        this.setData({canDelivery: result.supply, errorMsg: result.errorMsg})
      })
    },
    initCart(cartItems) {
      let totalFee = 0;
      let count = 0;
      let selectAll = true;
      let selectCartItems = [];
      for (let i = 0; i < cartItems.length; i++) {
        let cartItem = cartItems[i];
        if (cartItem.selected && !cartItem.disable) {
          selectCartItems.push(cartItem)
          totalFee += cartItem.price * cartItem.num;
          count += cartItem.num;
        } else {
          selectAll = false;
        }
      }
      this.setData({count: count, totalFee: totalFee, selectAll: selectAll, selectCartItems: selectCartItems})
    },
    handleClear() {
      wx.showModal({
        title: "温馨提示", content: "是否需要清空购物车?",
        showCancel: true,
        success: sm => {
          if (sm.confirm) {
            let cartItemDel = [];
            this.data.cartItems.forEach(item => {
              let temp = {
                cartItemId: item.cartItemId,
                goodsId: item.goodsId,
                skuId: item.skuId,
                storeId: item.storeId,
              }
              cartItemDel.push(temp);
            })
            batchDeleteItem(cartItemDel).then(res => {
              this.setData({cartItems: [], dialogShow:false, count:0})
              this.refresh()
            })
          }
        }
      });
    },
    handleUpdateNum(e) {
      let data = e.detail;
      let cartItems = this.data.cartItems
      for (let i = 0; i < cartItems.length; i++) {
        if (data.cartItemId === cartItems[i].cartItemId) {
          cartItems[i].num = data.num;
        }
      }
      this.setData({cartItems: cartItems})
      this.initCart(cartItems)
    },
    handleUpdateSelect(e) {
      let data = e.detail;
      let cartItems = this.data.cartItems
      for (let i = 0; i < cartItems.length; i++) {
        if (data.cartItemId === cartItems[i].cartItemId) {
          cartItems[i].selected = data.selected;
        }
      }
      this.setData({cartItems: cartItems})
      this.initCart(cartItems)
    },

    handleSelectAll() {
      if (this.data.cart.errorCode !== 0) {
        return;
      }
      let cartItems = this.data.cartItems
      let selected = !this.data.selectAll;
      let cardItemIdList = [];
      if (this.data.selectAll) {
        // 取消所有选择
        for (let i = 0; i < cartItems.length; i++) {
          if (cartItems[i].disable) {
            continue;
          }
          cardItemIdList.push(cartItems[i].cartItemId)
          cartItems[i].selected = !this.data.selectAll;
        }
      } else {
        // 选择所有
        for (let i = 0; i < cartItems.length; i++) {
          if (cartItems[i].disable) {
            continue;
          }
          if (!cartItems[i].selected) {
            cardItemIdList.push(cartItems[i].cartItemId)
            cartItems[i].selected = true;
          }
        }
      }
      changeSelectState({selected, cardItemIdList}).then((res => {
      }))
      this.setData({cartItems})
      this.initCart(cartItems)
    },
    handleSelectStore() {
      this.triggerEvent('selectStore', {deliveryType: this.deliveryType});
    },
    handlePreOrder() {
      let selectCartList = this.data.selectCartItems;
      if (selectCartList.length === 0) {
        return;
      }
      wx.showLoading({ title: "下单中..." , mark: true});
      let orderPreForm = {
        items: [],
        source: 0,
        storeId: this.data.cart.storeId,
        type: this.data.deliveryType
      };
      selectCartList.forEach(item => {orderPreForm.items.push(item)})
      preOrderFun(orderPreForm).then(res => {
        wx.hideLoading();
        if (res.code === 0) {
          router.push({name: 'mall/submit-order', params: {preNo: res.data.preNo}})
        }
      })
    }
  }
});
